﻿using System.Collections.Generic;
using System.Diagnostics;
using System.Xml.Linq;

namespace Bing
{
    /// <summary>
    /// Contains an List of results returned for a request that specifies the RelatedSearch <see cref="ApiHelper.SourceType"/>.
    /// </summary>
    [DebuggerDisplay("Results: {Results.Count}, Errors: {Errors.Count}")]
    public class RelatedSearchResponse: SearchResponseBase
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="RelatedSearchResponse"/> class.
        /// </summary>
        public RelatedSearchResponse(XContainer element)
            : base(element)
        {
            Results = new List<RelatedSearchResult>();
        }

        /// <summary>
        /// Gets or sets the results.
        /// </summary>
        /// <value>The results.</value>
        public List<RelatedSearchResult> Results { get; set; }

        /// <summary>
        /// Parses the response from the Bing API.
        /// </summary>
        /// <param name="element">The XML from the Bing API</param>
        /// <returns>An <see cref="RelatedSearchResponse" /></returns>
        public static RelatedSearchResponse ParseElement(XContainer element)
        {
            RelatedSearchResponse relatedSearchResponse = new RelatedSearchResponse(element);
            if (relatedSearchResponse.Errors.Count > 0) return relatedSearchResponse;

            var relatedSearch = element.Element(XName.Get("RelatedSearch", ApiHelper.RelatedSearch));
            if (relatedSearch == null) return relatedSearchResponse;

            XElement relatedSearchesResults = relatedSearch.Element(XName.Get("Results", ApiHelper.RelatedSearch));
            if (relatedSearchesResults != null)
            {
                foreach (
                    XElement result in
                        relatedSearchesResults.Elements(XName.Get("RelatedSearchResult", ApiHelper.RelatedSearch)))
                {
                    RelatedSearchResult relatedSearchResult = new RelatedSearchResult();
                    relatedSearchResult.Title = ApiHelper.GetElementValueOrDefault<string>(result, "Title", ApiHelper.RelatedSearch);
                    relatedSearchResult.Url = ApiHelper.GetElementValueOrDefault<string>(result, "Url", ApiHelper.RelatedSearch);
                    relatedSearchResponse.Results.Add(relatedSearchResult);
                }
            }

            return relatedSearchResponse;
        }
    }
}
